package org.jeecg.modules.demo.com.kunpeng.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.demo.com.kunpeng.entity.*;
import org.jeecg.modules.demo.com.kunpeng.service.IProjectService;
import org.jeecg.modules.demo.com.kunpeng.entity.dto.ProjectListQueryDTO;
import org.jeecg.modules.demo.com.kunpeng.ex.ServiceCode;
import org.jeecg.modules.demo.com.kunpeng.ex.ServiceException;
import org.jeecg.modules.demo.com.kunpeng.mapper.ProjectDetailsFileMapper;
import org.jeecg.modules.demo.com.kunpeng.mapper.ProjectDetailsMapper;
import org.jeecg.modules.demo.com.kunpeng.mapper.ProjectMapper;
import org.jeecg.modules.demo.com.kunpeng.service.ISaleContractDetailService;
import org.jeecg.modules.demo.com.kunpeng.service.ISaleContractService;
import org.jeecg.modules.demo.com.kunpeng.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;

/**
 * @Description: 项目表
 * @Author: jeecg-boot
 * @Date:   2022-12-03
 * @Version: V1.0
 */
@Service
@Slf4j
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements IProjectService {

	private static Integer PROJECT_SUFFIX;

	@Autowired
	private ProjectMapper projectMapper;
	@Autowired
	private ProjectDetailsMapper projectDetailsMapper;
	@Autowired
	private ProjectDetailsFileMapper projectDetailsFileMapper;
	@Autowired
	private ISaleContractService saleContractService;
	@Autowired
	private ISaleContractDetailService saleContractDetailService;
	/**
	 * 给项目表，项目详情表，项目详情文件表分别插入数据
	 * @param project
	 * @param projectDetailsInsertList
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(Project project, List<ProjectDetailsInsert> projectDetailsInsertList) {
		ProjectStandardVO projectStandardVO = projectMapper.selectByProjectName(project.getProjectName());
		if(null!=projectStandardVO){
			log.info("该项目已存在，请重新插入！");
			throw new ServiceException(ServiceCode.ERR_INSERT,"该项目已存在，请重新插入！");
		}

		if(null!=projectDetailsInsertList){
			project.setResponsibilityPerson(projectDetailsInsertList.get(0).getCommander());
		}

		project.setAlreadyReturnMoney(new BigDecimal(0));
		projectMapper.insert(project);
		log.info("项目表插入数据成功！");
		//根据合同编号获取合同数据
		List<SaleContractVO> saleContractVOS = saleContractService.selectBySaleContractId(project.getAgreementId());
		if(saleContractVOS.size()>0){
			for(SaleContractVO saleContractVO:saleContractVOS){
				//如果合同关联项目名称为null则修改名称为当前插入项目名
				if(saleContractVO.getProjectName().length()==0 || saleContractVO.getProjectName().equals("")){//如果合同的关联项目为null，则直接修改
					saleContractService.updateProjectNameById(saleContractVO.getId(),project.getProjectName());
				}else{																	 //如果关联项目不为null，判断是否包含当前项目，不包含，则拼接
					String projectName=saleContractVO.getProjectName();
					if(!projectName.equals(project.getProjectName())){
						String linkProjectName=saleContractVO.getProjectName()+","+project.getProjectName();
						saleContractService.updateProjectNameById(saleContractVO.getId(),linkProjectName);
					}
				}
				//销售合同id，项目（id），项目编号，项目名称
				List<SaleContractDetail> saleContractDetails = saleContractDetailService.selectByMainId(saleContractVO.getId());
				if (saleContractDetails.size()>0){
					for (SaleContractDetail saleContractDetail:saleContractDetails){
						if(saleContractDetail.getProjectName().equals(project.getProjectName())){
							String message="项目【"+project.getProjectName()+"】已关联合同【"+saleContractVO.getContractName()+"】,请重新填写！";
							throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
						}
					}
				}
				SaleContractDetail saleContractDetail=new SaleContractDetail();
				saleContractDetail.setScid(saleContractVO.getId());
				saleContractDetail.setPjid(project.getId());
				saleContractDetail.setProjectId(project.getProjectId());
				saleContractDetail.setProjectName(project.getProjectName());
				saleContractDetail.setTotalAmount(new BigDecimal(0));
				saleContractDetail.setTaxRate(0.0);
				saleContractDetail.setTaxAmount(new BigDecimal(0));
				saleContractDetail.setDiscountRate(0.0);
				saleContractDetail.setContractAmount(new BigDecimal(0));
				saleContractDetailService.insert(saleContractDetail);
			}
		}

		if(projectDetailsInsertList!=null && projectDetailsInsertList.size()>0) {
			//遍历并添加到集合中
			for(ProjectDetailsInsert p:projectDetailsInsertList){
				//创建一个不包含文件列表的项目详情对象，复制数据
				System.out.println("****p:"+p.toString());
				ProjectDetails projectDetails=new ProjectDetails();
				BeanUtils.copyProperties(p,projectDetails);
				//插入项目id进行插入
				projectDetails.setId(null);
				projectDetails.setPjId(project.getId());
				projectDetailsMapper.insert(projectDetails);
				log.info("项目详情表数据插入成功！");
				//获取文件列表数据
				List<ProjectDetailsFile> fileList = p.getFileList();
				if(fileList!=null && fileList.size()>0){
					for (ProjectDetailsFile f:fileList) {
						//插入项目id和项目详情id插入到项目详情文件表
						f.setPdId(projectDetails.getId());
						f.setPjId(project.getId());
						projectDetailsFileMapper.insert(f);
						log.info("文件表插入成功！");
					}
				}
			}
		}
	}

	/**
	 * 根据项目id分别修改三个表数据
	 * @param project
	 * @param projectDetailsInsertList*/

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(Project project,List<ProjectDetailsInsert> projectDetailsInsertList) {
		System.out.println("项目列表编辑提交的项目数据："+project.toString());
		projectMapper.updateById(project);
		
		//1.先删除项目详情表和项目详情文件表数据
		projectDetailsMapper.deleteByMainId(project.getId());
		projectDetailsFileMapper.deleteByMainId(project.getId());
		
		//2.子表数据重新插入
		if(projectDetailsInsertList!=null && projectDetailsInsertList.size()>0) {
			//复制数据重新插入到项目详情表
			for (ProjectDetailsInsert p:projectDetailsInsertList) {
				ProjectDetails projectDetails=new ProjectDetails();
				BeanUtils.copyProperties(p,projectDetails);
				projectDetails.setId(null);
				projectDetails.setPjId(project.getId());
				projectDetailsMapper.insert(projectDetails);
				//重新插入项目详情文件表数据
				List<ProjectDetailsFile> fileList = p.getFileList();
				if(fileList!=null&&fileList.size()>0) {
					for (ProjectDetailsFile f : fileList) {
						f.setPjId(project.getId());
						f.setPdId(projectDetails.getId());
						projectDetailsFileMapper.insert(f);
					}
				}
			}
		}
	}

	/**
	 * 根据项目表id删除数据
	 * @param id*/

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		projectDetailsMapper.deleteByMainId(id);
		projectMapper.deleteById(id);
		projectDetailsFileMapper.deleteByMainId(id);
	}

	/**
	 * 根据项目id批量删除
	 * @param idList*/

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			projectDetailsMapper.deleteByMainId(id.toString());
			projectMapper.deleteById(id);
			projectDetailsFileMapper.deleteByMainId(id.toString());
		}
	}

	/**
	 * 根据关键字查询项目表列表
	 * @param page
	 * @param projectListQueryDTO
	 * @return*/

	@Override
	public Page<ProjectListQueryVO> listByKeyWords(Page<ProjectListQueryVO> page, ProjectListQueryDTO projectListQueryDTO) {
		log.info("开始处理根据关键性查询项目列表：service");

		Page<ProjectListQueryVO> list = page.setRecords(projectMapper.listByKeyWords(page, projectListQueryDTO.getAgreementId(), projectListQueryDTO.getExecutionStatus(),
				projectListQueryDTO.getCustomerName(), projectListQueryDTO.getProjectName(),
				projectListQueryDTO.getResponsibilityPerson(), projectListQueryDTO.getKeyWords()));

		//给项目当前进度赋值
		for (ProjectListQueryVO projectListQueryVO:list.getRecords()) {
			//回款状态
			if(null!=projectListQueryVO.getAlreadyReturnMoney() && projectListQueryVO.getAlreadyReturnMoney().compareTo(projectListQueryVO.getReturnMoney())==-1){
				log.info("项目【"+projectListQueryVO.getProjectName()+"】回款状态为1");
				projectListQueryVO.setReturnMoneyStatus(1);
			}else if(null!=projectListQueryVO.getAlreadyReturnMoney() && projectListQueryVO.getAlreadyReturnMoney().compareTo(projectListQueryVO.getReturnMoney())==0){
				log.info("项目【"+projectListQueryVO.getProjectName()+"】回款状态为2");
				projectListQueryVO.setReturnMoneyStatus(2);
			}

			if (!(projectListQueryVO.getStartTime()==null || projectListQueryVO.getEndTime()==null)) {
				Integer completesSpeed = projectListQueryVO.getCompletesSpeed();
				long nowTimeMillis = System.currentTimeMillis();
				Calendar cal=Calendar.getInstance();
				cal.setTime(projectListQueryVO.getStartTime());
				long startTimeMillis = cal.getTimeInMillis();
				cal.setTime(projectListQueryVO.getEndTime());
				Long endTimeMillis=cal.getTimeInMillis();
				Long seTime=endTimeMillis-startTimeMillis;
				Long snTime=nowTimeMillis-startTimeMillis;
				if(snTime>seTime){
					completesSpeed=100;
                    projectMapper.updateExecutionStatusById(projectListQueryVO.getId(),"3");
				}else if(startTimeMillis>nowTimeMillis) {
                    projectMapper.updateExecutionStatusById(projectListQueryVO.getId(),"1");
                    completesSpeed=0;
                }else if(seTime>snTime){
                    Double st = seTime.doubleValue();
                    Double sn = snTime.doubleValue();
                    Double temp=((sn/st)*100);
                    System.out.println("temp:"+temp);
                    completesSpeed=temp.intValue();
                    projectMapper.updateExecutionStatusById(projectListQueryVO.getId(),"2");
                }
				projectListQueryVO.setCompletesSpeed(completesSpeed);
				System.out.println("completesSpeed:"+completesSpeed);
			}
			//给项目当前阶段赋值
			//获取当前日期
			Long nowTimeMillis = System.currentTimeMillis();
			System.out.println("当前时间："+nowTimeMillis);
			String mainId=projectListQueryVO.getId();
			List<ProjectDetails> projectDetailsList = projectDetailsMapper.selectByMainId(mainId);
			System.out.println("根据项目id：【"+mainId+"】获取到的项目详情列表数据长度："+projectDetailsList.size());
			if(projectDetailsList.size()>0){
				for(ProjectDetails projectDetails:projectDetailsList){
					System.out.println("projectDetails:"+projectDetails.toString());
					Calendar cal=Calendar.getInstance();
					cal.setTime(projectDetails.getStartTime());
					Long startTimeMillis = cal.getTimeInMillis();
					System.out.println("项目开始时间："+startTimeMillis);
					cal.setTime(projectDetails.getEndTime());
					Long endTimeMillis = cal.getTimeInMillis();
					System.out.println("项目结束时间："+endTimeMillis);
					System.out.println("nowTimeMillis:"+nowTimeMillis);
					System.out.println("startTimeMillis:"+startTimeMillis);
					System.out.println("endTimeMillis:"+endTimeMillis);
					if(nowTimeMillis>startTimeMillis && nowTimeMillis<endTimeMillis){
						//项目阶段赋值
						System.out.println("11111111111111111111");
						projectListQueryVO.setCurrentSpeed(projectDetails.getProjectPhase());
						System.out.println("projectId"+projectDetails.getPjId());
						System.out.println("projectPhase:"+projectDetails.getProjectPhase());
						projectMapper.updateCurrentSpeed(projectDetails.getPjId(),projectDetails.getProjectPhase());
					}
				}
			}

		}
		return list;
	}

	/**
	 * 根据项目id查询项目详情
	 * @param projectId
	 * @return*/

	@Override
	public ProjectStandardVO selectByProjectId(String projectId) {
		log.info("开始根据项目名称查询项目表详情：service");
		ProjectStandardVO projectStandardVO = projectMapper.selectByProjectId(projectId);
		if(projectStandardVO==null){
			String message="该项目不存在！请与管理员联系！";
			throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
		}
		return projectStandardVO;
	}

	/**
	 * 获取客户列表
	 * @return*/

	@Override
	public List<CustomerInNameListVO> customerList() {
		log.info("开始获取客户名称集合：service");
		List<CustomerInNameListVO> customerInNameListVOS = projectMapper.customerList();
		return customerInNameListVOS;
	}

	/**
	 * 根据项目id获取项目起始时间
	 * @param projectId
	 * @return*/

	@Override
	public List<ProjectDateReturn> selectProjectDetailsDate(String projectId) {
		List<ProjectDate> projectDates = projectMapper.selectProjectDetailsDate(projectId);
		for (ProjectDate p:projectDates) {
			System.out.println("项目阶段数据："+p.toString());
		}
		List<ProjectDateReturn> projectDateReturnList=new ArrayList<>();
		for (ProjectDate projectDate:projectDates) {
			//设置时间格式
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String startTime = sdf.format(projectDate.getStartTime());
			String endTime=sdf.format(projectDate.getEndTime());
			//创建返回的日期对象并赋值
			ProjectDateReturn projectDateReturn=new ProjectDateReturn();
			LocalDate parseStartTime = LocalDate.parse(startTime);
			LocalDate parseEndTime = LocalDate.parse(endTime);
			projectDateReturn.setStartTime(parseStartTime);
			projectDateReturn.setEndTime(parseEndTime);
			projectDateReturn.setId(projectDate.getId());
			//项目阶段
			projectDateReturn.setProjectPhase(projectDate.getProjectPhase());
			//项目负责人
			projectDateReturn.setResponsibilityPerson(projectDate.getCommander());
			projectDateReturnList.add(projectDateReturn);
		}
		return projectDateReturnList;
	}

	/**
	 * 根据项目编号获取项目名称
	 * @param projectId
	 * @return*/

	@Override
	public String selectProjectNameByProjectId(String projectId) {
		String projectName = projectMapper.selectProjectNameByProjectId(projectId);
		return projectName;
	}

	/**
	 * 根据项目表id修改项目回款状态
	 * @param projectId
	 * @param returnMoneyStatus
	 * @return*/

	@Override
	public void updateReturnMoneyStatus(String projectId, String returnMoneyStatus) {
		//执行修改受影响的行数
		int num = projectMapper.updateReturnMoneyStatus(projectId, returnMoneyStatus);
		if(num!=1){
			String message="修改失败，请联系管理员！";
			throw new ServiceException(ServiceCode.ERR_UPDATE,message);
		}
	}

	/**
	 * 根据项目id查询项目起止时间
	 * @param id
	 * @return*/

	@Override
	public List<DateRange> projectStartEndTime(String id) {
		Project project = projectMapper.selectProjectStartEndTimeById(id);
		List<DateRange> list = new ArrayList<>();
		DateRange dr = null;
		//转换时间类型为localData
		Instant instant = project.getStartTime().toInstant();
		LocalDate stDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();
		//转换时间类型为localData
		instant = project.getEndTime().toInstant();
		LocalDate enDate = instant.atZone(ZoneId.systemDefault()).toLocalDate().plusDays(1);

		Integer rangeId=0;
		while (stDate.isBefore(enDate)) {
			int week = stDate.getDayOfWeek().getValue();

			if (dr == null || week == 1) {
				dr = new DateRange();
				dr.setStartDate(stDate);
			}
			if (week == 7 || stDate.compareTo(instant.atZone(ZoneId.systemDefault()).toLocalDate()) == 0) {
				dr.setEndDate(stDate);
				list.add(dr);
				dr.setId(rangeId++);
			}
			stDate = stDate.plusDays(1);
		}
		return list;
	}

	/**
	 * 根据项目编号模糊查询*/

	@Override
	public Integer listProjectIdByPrefix(String prefix) {
		List<Project> projects = projectMapper.listProjectIdByPrefix(prefix);
		for (Project project:projects) {
			System.out.println("根据前缀查询到的项目数据："+project.toString());
		}
		if(projects.size()>0){
			Project project = projects.get(projects.size() - 1);
			String projectId = project.getProjectId();
			String substring = projectId.substring(10, 13);
			PROJECT_SUFFIX = Integer.parseInt(substring)+1;
		}else {
			PROJECT_SUFFIX=1;
		}
		return PROJECT_SUFFIX;
	}

	/**
	 * 根据客户名称获取项目名称和编号
	 * @param customerName
	 * @return*/

	@Override
	public List<ProjectVO> listProjectByCustomerName(String customerName) {
		List<Project> customerList = projectMapper.listProjectByCustomerName(customerName);
		List<ProjectVO> projectVOList=new ArrayList<>();
		Integer key=1;
		if(customerList.size()>0){
			for (Project project:customerList) {
				ProjectVO projectVO=new ProjectVO();
				BeanUtils.copyProperties(project,projectVO);
				projectVO.setKey(key++);
				projectVOList.add(projectVO);
			}
		}
		return projectVOList;
	}

	/**
	 * 根据项目名称获取项目详情
	 * @param projectName
	 * @return*/

	@Override
	public List<String> listProjectPhaseByMainId(String projectName) {
		if(projectName!=null || projectName!="" || projectName.length()>0) {
			Project project = projectMapper.selectProjectByProjectName(projectName);
			List<String> projectPhaseList = projectDetailsMapper.listProjectPhaseByMainId(project.getId());
			return projectPhaseList;
		}
		return null;
	}


	/**
	 * 根据id修改已回款金额
	 * @param id
	 * @param alreadyReturnMoney*/

	@Override
	@Transactional
	public void updateAlreadyReturnMoney(String id, BigDecimal alreadyReturnMoney) {
		//根据id查询项目
		Project project = projectMapper.selectById(id);
		//查询项目的当前已回款金额
		BigDecimal alrReturnMoney = project.getAlreadyReturnMoney();
		log.info("该项目当前已回款金额:"+alreadyReturnMoney);
		//判断当前已回款金额加上新的金额是否超过项目金额，超过报异常
		alrReturnMoney=alrReturnMoney.add(alreadyReturnMoney);
		log.info("当前回款和新金额相加:"+alrReturnMoney);
		if(alrReturnMoney.compareTo(project.getReturnMoney())==1){
			String message="已回款金额超出项目金额，请重新输入！";
			throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
		}
		//不超过，修改数据库的已回款金额值
		BigDecimal newAlreadyReturnMoney = project.getAlreadyReturnMoney().add(alreadyReturnMoney);
		projectMapper.updateAlreadyReturnMoney(id,newAlreadyReturnMoney);
	}
}
